<?php 
namespace Common\Controller;
use Think\Controller;
class BaseController extends Controller{
	
	/**
	 * 初始化方法，统一的权限控制
	 */
	 public function _initialize(){
		/* $auth=new \Think\Auth();
		 $ruleName=MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME;*/
		 
		$authids = $this->get_menu_id(); //获取权限id数组
		$cur_auth = $authids[strtolower(MODULE_NAME)][strtolower(CONTROLLER_NAME )][strtolower(ACTION_NAME)];//当前模块权限id
		
		
		if($cur_auth){
			
			$rules=$this->get_uid_rules();
			if($_SESSION['loginUser']['role'] != 'SUPER_ADMIN'){
				if(!in_array($cur_auth,$rules)){
						/*$this->error("没有访问权限");*/
						echo "<script>alert('没有访问权限')</script>";
						die();
				}
			}
		}
		
		 
		/* $result=$auth->check($ruleName,$_SESSION['loginUser']['uid']);//统一的权限控制
		 if(!$result){
		 	$this->error('您没有权限访问');
		 }*/
		  
		
	}
	public function get_menu_id(){
		$rules = M('AuthRule')->select();
		$data = array();
		foreach($rules as $r){
			$tmp = explode('.', $r['name']);
			$tmp = explode('/', $tmp[0]);
			$_group = strtolower($tmp[1]);
			$_module = strtolower($tmp[2]);
			$tmp[3] ? $_action = $tmp[3] : $_action = 'index';
			$data[$_group][$_module][$_action] = $r['id']; //权限ID对应
		}
		//print_r($data);
		return $data;
	} 
	//获取当前权限数组
	public function get_uid_rules(){
		if(!$_SESSION['loginUser']["role"])$this->error("请登录");
		$map['group']=$_SESSION['loginUser']["role"];
		
		$groups = M('AuthGroup')->where($map)->find();
		$group=explode(",",$groups["rules"]);
		return $group;
	}

	/**
	 * 校验提交上来的验证码
	 * @param unknown $key
	 * @param unknown $token
	 */
	public function _check_token($key,$token){
		if(!$token){
			_apiReturn(0, L('error_info_token_1'));
		}
		
		if(!token_check('login', $token)){
			_apiReturn(0, L('error_info_token_2'));
		}
	}

	public function _del($m,$ids){
		if ( empty($ids) ) {
			_apiReturn(0, "请设置删除数据ID");
		}
		$map = array($m->getPk() => array('in', $ids));
		$lists = $m->where($map)->select();
		if($m->where($map)->delete()){ //删除本地数据库中的row
			_apiReturn(1, "删除成功");
		} else {
			_apiReturn(0, "删除失败",$m->_sql());
		}
	}
	
	public function _delbyuser($m,$ids,$uid){
		if ( empty($ids) ) {
			_apiReturn(0, "请设置删除数据ID");
		}
		$map = array($m->getPk() => array('in', $ids));
		$lists = $m->where($map)->select();
		if($uid){
			foreach($lists as $vo){
				if($vo['uid'] != $uid){
					_apiReturn(0, '有您没有权限删除的数据，无法删除', $data, $url);
				}
			}
		}
		if($m->where($map)->delete()){ //删除本地数据库中的row
			_apiReturn(1, "删除成功");
		} else {
			_apiReturn(0, "删除失败");
		}
	}
}
?>